package com.putao.album.guide;

import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.loopj.android.http.RequestParams;
import com.putao.album.R;
import com.putao.album.base.BaseActivity;
import com.putao.album.base.BaseFragment;
import com.putao.album.util.AppHelper;
import com.putao.album.util.CommonUtils;
import com.putao.album.util.DisplayHelper;
import com.putao.album.util.HttpRequestUtil;
import com.putao.album.util.PuTaoConstants;
import com.putao.album.util.SharedPreferencesHelper;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by jidongdong on 15/4/23.
 */
public class ActivityGuide extends BaseActivity {
    private ViewPager guide_pager;
    private boolean mFirstLaunch = false;
    private int mLastVersionCode = 0;
    int currentVercode = AppHelper.getVersionCode();
    private boolean mNewVersion = false;
    private boolean mShowSplash = false;
    private boolean fromAbout;
    private boolean misScrolled;
    private LinearLayout page_index_icon;
    private int pageNum = 3;
    private ImageView[] imageIcons = new ImageView[pageNum];
    private ArrayList<IGuideAnimation> fragments = new ArrayList<IGuideAnimation>();
    private int lastpos = 0;


    @Override
    public void doBefore() {
        mLastVersionCode = SharedPreferencesHelper.readIntValue(mContext, PuTaoConstants.PREFERENCE_KEY_VERSIONCODE, 0);
        mFirstLaunch = SharedPreferencesHelper.readBooleanValue(mContext, PuTaoConstants.PREFERENCE_KEY_FIRST_LAUNCH, true);
        if (!mFirstLaunch && currentVercode <= mLastVersionCode) {//非第一次启动或有版本更新
            mShowSplash = true;
        }
    }

    @Override
    public int doGetContentViewId() {
        return R.layout.activity_guide;
    }

    @Override
    public void doInitSubViews(View view) {
        guide_pager = queryViewById(R.id.guide_pager);
        page_index_icon = queryViewById(R.id.page_index_icon);
    }

    void initIcons() {
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        params.leftMargin = 10;
        params.rightMargin = 10;
        for (int i = 0; i < pageNum; i++) {
            imageIcons[i] = new ImageView(this);
            imageIcons[i].setBackgroundResource(R.drawable.dot_unselected);
            imageIcons[i].setLayoutParams(params);
            page_index_icon.addView(imageIcons[i]);
        }
        setCurrentPageIcon(0);
    }

    void setCurrentPageIcon(int index) {
        for (int i = 0; i < pageNum; i++) {
            imageIcons[i].setBackgroundResource((i == index) ? R.drawable.dot_selected : R.drawable.dot_unselected);
        }
    }

    @Override
    public void doInitData() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            fromAbout = bundle.getBoolean("fromAbout", false);
        }

        if (mFirstLaunch) {
            SharedPreferencesHelper.saveBooleanValue(mContext, PuTaoConstants.PREFERENCE_KEY_FIRST_LAUNCH, false);
        }
        if (currentVercode > mLastVersionCode) {
            if (!mFirstLaunch)
                mNewVersion = true;
            SharedPreferencesHelper.saveIntValue(mContext, PuTaoConstants.PREFERENCE_KEY_VERSIONCODE, currentVercode);
        }
        //TODO:根据逻辑判断显示闪屏还是引导页
        if (mShowSplash && !fromAbout) {
            setSplashFragments();
        } else {
            setGuideFragments();
        }
        postUmengToken();
    }

    void postUmengToken() {
        RequestParams params = new RequestParams(HttpRequestUtil.buildHttpRequestParams(new HashMap()));
        params.put("umeng_device_token", CommonUtils.getUmengDeviceToken());
        params.put("baby_id", CommonUtils.getBabyId());
        HttpRequestUtil.doHttpPostRequest(mContext, PuTaoConstants.API_REGISTER_SUCESS_CALLBACK, params, null);
    }

    private void setSplashFragments() {

        SplashFragment fragment = new SplashFragment();
        fragments.add(fragment);
        guide_pager.setAdapter(new GuidePagerAdapter(getSupportFragmentManager(), fragments));
    }


    private void setGuideFragments() {
        initIcons();
        for (int i = 0; i < pageNum; i++) {
            GuideFragment fragment = new GuideFragment();
            Bundle bundle = new Bundle();
            bundle.putInt("index", i);
            bundle.putBoolean("showbtn", (i == (pageNum - 1)) && !fromAbout ? true : false);
            bundle.putBoolean("newver", mNewVersion);
            fragment.setArguments(bundle);
            fragments.add(fragment);
        }
        guide_pager.setOffscreenPageLimit(pageNum);
        guide_pager.setAdapter(new GuidePagerAdapter(getSupportFragmentManager(), fragments));
        guide_pager.setOnPageChangeListener(mPageChangeListener);
    }

    ViewPager.OnPageChangeListener mPageChangeListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            int distance = positionOffsetPixels;
            if ((lastpos == position) && (position < fragments.size() - 1)) {
                if (position > 0) {
                    fragments.get(position).Move(DisplayHelper.getScreenWidth() + distance);
                } else {
                    fragments.get(position).Move(distance);
                }
                fragments.get(position + 1).Move(distance);
            }
            lastpos = position;
        }

        @Override
        public void onPageSelected(int position) {
        }

        @Override
        public void onPageScrollStateChanged(int state) {
            switch (state) {
                case ViewPager.SCROLL_STATE_DRAGGING:
                    misScrolled = false;
                    break;
                case ViewPager.SCROLL_STATE_SETTLING:
                    misScrolled = true;
                    break;
                case ViewPager.SCROLL_STATE_IDLE:
                    int current = guide_pager.getCurrentItem();
                    if ((current == pageNum - 1) && !misScrolled && fromAbout) {
                        finish();
                    }
                    IGuideAnimation ani = fragments.get(current);
                    ani.Play();
                    misScrolled = true;
                    setCurrentPageIcon(current);
                    break;
            }
        }
    };

    @Override
    public void onClick(View v) {

    }


    public class GuidePagerAdapter<T extends BaseFragment> extends FragmentPagerAdapter {
        private ArrayList<T> mFragments;

        public GuidePagerAdapter(FragmentManager fm, ArrayList<T> fragments) {
            super(fm);
            mFragments = fragments;
        }

        @Override
        public T getItem(int i) {
            return mFragments == null ? null : mFragments.get(i);
        }

        @Override
        public int getCount() {
            return mFragments == null ? 0 : mFragments.size();
        }
    }
}
